const { getSqlLiteData } = require('../../../SqlLiteDB');
const pathLib = require('path');
const fs = require('fs');

module.exports = function setUploadFileRouter (router) {

    let rename = function (path, filename) {
        return new Promise((resolve, reject) => {
            fs.rename(path, filename, function (err) {
                if (err) {
                    resolve(err);
                } else {
                    resolve('上传成功');
                }
            });
        });
    };
    //上传文件
    router.post('/uploadFiles', async function (req, res, next) {
        try {
            // 上传的文件在req.files中
            let dataContent = JSON.parse(req.body['dataContent']);
            let files = dataContent.files;
            let uploadResultArr = [];
            for (let i = 0; i < files.length; i++) {
                // const filename = files[i].path + pathLib.parse(files[i].originalname).ext;
                // console.log(filename);
                let uploadResult = await writeFile(files[i]);
                uploadResultArr.push(uploadResult);
            }
            res.status(200).json({
                result: uploadResultArr,
            });
        }
        catch (ex) {
            res.status(500).json({
                result: ex,
            });
            console.log('ex :>> ', {
                result: ex,
            });
        }
    });

    let writeFile = function (file) {
        return new Promise((resolve, reject) => {
            let folderIndex = file.path.lastIndexOf('/');
            let folderPath = file.path.slice(0, folderIndex);
            let isPathExist = false;
            fs.mkdir(folderPath, { recursive: true }, (folderErr) => {
                if (folderErr) {
                    if (folderErr.code == 'EEXIST') {
                        isPathExist = true;
                    }
                    else {
                        resolve('文件夹检测失败' + folderErr);
                    }
                }
                else {
                    isPathExist = true;
                }
                if (isPathExist) {
                    let base64 = file.base64.split(';base64,').pop();
                    fs.writeFile(file.path, base64, { encoding: 'base64' }, function (err) {
                        if (err) {
                            console.log('File save err:' + err);
                            resolve(err);
                        }
                        else {
                            resolve('文件保存成功');
                        }
                    });
                }
            });

        });
    };
};
